package com.trainoo.novel.util;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.MessageFormat;

/**
 * Created by Administrator on 2018/8/8.
 */
public class UrlDownLoader {

    private static Logger logger = LoggerFactory.getLogger(UrlDownLoader.class);

    private static Integer RETRY = 5;

    public static Document download(String newUrl) throws RuntimeException{
        return download(newUrl, RETRY);
    }

    private static Document download(String newUrl, int n) throws RuntimeException{
        if(n > 0) {
            try {
                return Jsoup.connect(newUrl).userAgent("Mozilla").get();
            } catch (IOException e) {
                logger.error(MessageFormat.format("获取[{0}]失败，正在尝试第[{1}]次重连...", newUrl, RETRY - n + 1));
                return download(newUrl, n - 1);
            }
        }else{
            throw new RuntimeException("网络连接超时，请重试！");
        }
    }
}
